import { Popover } from "antd";
import { ChevronRight } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { useLocation, useNavigate } from "react-router";
import type { IMenuItem } from "~/types/manage";
import { cn } from "~/utils/ui.util";

interface Props {
  menu: IMenuItem;
  onClick?: (item: IMenuItem) => void;
  className?: string;
  collapsed?: boolean;
}

/**
 * 菜单组件
 * @param props
 * @returns
 */
export default function Menu(props: Props) {
  const navigate = useNavigate();
  const location = useLocation();
  const [menu, setMenu] = useState<IMenuItem>(props.menu || null);
  const subMenuRef = useRef<HTMLDivElement | null>(null);

  const _handleClick = () => {
    // 没有子菜单，点击直接跳转
    if (!menu?.children || menu?.children.length === 0) {
      menu.path && navigate(menu.path);
    }
    // 有子菜单，点击展开子菜单
    if (menu?.children && menu?.children.length > 0) {
      setMenu({
        ...menu,
        isOpen: !menu.isOpen,
      });
    }
  };

  // 判断是否有子菜单
  const hasSubMenu = useMemo(() => {
    return menu?.children && menu?.children.length > 0;
  }, [menu?.children]);

  useEffect(() => {
    if (
      hasSubMenu &&
      props.menu?.path &&
      location.pathname.startsWith(props.menu?.path)
    ) {
      setMenu({
        ...props.menu,
        isOpen: true,
      });
    }
  }, [props.menu, props.collapsed]);

  return (
    <div className={cn("flex flex-col", props.className)}>
      <div
        className={cn(
          "flex cursor-default items-center gap-2 rounded-xl p-2 transition duration-300 ease-in-out",
          {
            "bg-gray-200 shadow":
              location.pathname === menu.path ||
              (props.collapsed &&
                menu.children?.find((item) => item.path === location.pathname)),
            "hover:bg-gray-100": location.pathname !== menu.path,
          },
          props.className,
        )}
        onClick={_handleClick}
      >
        {/* 当 collapsed 为true，鼠标悬浮显示弹窗 */}
        {props.collapsed && (
          <Popover
            placement="rightTop"
            title={menu.label}
            content={
              <div
                ref={subMenuRef}
                className={cn(
                  "mt-2 flex flex-col gap-2 overflow-hidden transition-all duration-300 ease-in-out",
                )}
              >
                {props.menu?.children?.map((item) => {
                  return (
                    <Menu
                      key={item.path}
                      className={"text-[14px] text-gray-600"}
                      menu={item}
                    />
                  );
                })}
              </div>
            }
          >
            <div
              className={cn("flex items-center justify-center p-1", {
                "text-[#1677ff]": location.pathname === menu.path,
              })}
            >
              <menu.icon size={18} />
            </div>
          </Popover>
        )}
        {!props.collapsed && (
          <>
            {menu.icon && (
              <div
                className={cn("flex items-center justify-center p-1", {
                  "text-[#1677ff]": location.pathname === menu.path,
                })}
              >
                <menu.icon size={18} />
              </div>
            )}
            <span
              className={cn(
                "flex-1 whitespace-nowrap transition-all duration-300",
              )}
            >
              {menu.label}
            </span>
            <ChevronRight
              className={cn("opacity-30 transition-all duration-300", {
                "w-auto rotate-90 opacity-100": menu.isOpen,
                hidden: !hasSubMenu,
              })}
              size={18}
            />
          </>
        )}
      </div>

      {/* 子菜单 */}
      {!props.collapsed && (
        <div
          ref={subMenuRef}
          className={cn(
            "flex flex-col gap-2 overflow-hidden transition-all duration-300 ease-in-out",
            {
              "mt-2": menu.isOpen,
            },
          )}
          style={{
            height: menu.isOpen ? subMenuRef.current?.scrollHeight + "px" : "0",
            visibility: menu.isOpen ? "visible" : "hidden",
          }}
        >
          {props.menu?.children?.map((item) => {
            return (
              <Menu
                key={item.path}
                className={"pl-2 text-[14px] text-gray-600"}
                menu={item}
              />
            );
          })}
        </div>
      )}
    </div>
  );
}
